package com.ncepu.jjojcodesandbox.controller;

import com.ncepu.jjojcodesandbox.JavaNativeCodeSandBox;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeRequest;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author simon_jiang
 * @version 1.0
 */
@RestController("/")
public class CodeSandBoxController {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";


    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @PostMapping("/execute")
    public ExecuteCodeResponse execute(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                       HttpServletResponse response) {
        // 基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null) {
            throw new RuntimeException("请求参数不能为空");
        }

        System.out.println("开始执行：");
        return javaNativeCodeSandBox.executeCode(executeCodeRequest);
    }

    @GetMapping("/health")
    public String HealthCheck() {
        return "ok";
    }
}
